#include <stdio.h>
#include <string.h>
#include "common_func.h"

void print_data(const char *buffer_name, const unsigned char *buffer, const int buffer_length, const int column_length)
{
    int i, j;

    if (buffer == NULL)
    {
        printf("Buffer is NULL.\n");
        return;
    }

    if (buffer_length <= 0)
    {
        printf("Buffer length must be greater than zero.\n");
        return;
    }

    if (column_length <= 0)
    {
        printf("Column length must be greater than zero.\n");
        return;
    }

    if (buffer_name == NULL)
    {
        printf("No Name[%d]\n", buffer_length);
    }
    else
    {
        printf("%s[%d]\n", buffer_name, buffer_length);
    }

    for (i = 0; i < buffer_length / column_length; i++)
    {
        printf("[0x%08x]: ", i * column_length);
        for (j = 0; j < column_length; j++)
        {
            printf("%02x ", buffer[i * column_length + j]);
        }
        printf("\b\n");
    }

    if (buffer_length % column_length == 0)
    {
        return;
    }

    printf("[0x%08x]: ", column_length * (buffer_length / column_length));
    for (i = buffer_length - (buffer_length % column_length); i < buffer_length; i++)
    {
        printf("%02x ", buffer[i]);
    }
    printf("\b\n");
    return;
}

void hex2str(char *input, int input_len, char *output)
{
    char *hexEncode = "0123456789ABCDEF";
    int i = 0, j = 0;

    for (i = 0; i < input_len; i++)
    {
        output[j++] = hexEncode[(input[i] >> 4) & 0xf];
        output[j++] = hexEncode[(input[i]) & 0xf];
    }
    output[j] = '\0';
    return;
}

static char hex2dec(char hex)
{
    if (hex >= '0' && hex <= '9')
    {
        return (char)(hex - '0');
    }
    if (hex >= 'a' && hex <= 'f')
    {
        return (char)(hex - 'a' + 10);
    }
    if (hex >= 'A' && hex <= 'F')
    {
        return (char)(hex - 'A' + 10);
    }
    return 0;
}

int str2hex(char *input, char *output, int *output_len)
{
    int i = 0;
    int input_len = 0;
    char ch0 = 0, ch1 = 0;

    input_len = (int)strlen(input);
    if (input_len % 2 != 0)
    {
        return -1;
    }

    while (i < input_len / 2)
    {
        ch0 = hex2dec(input[2 * i]);
        ch1 = hex2dec(input[2 * i + 1]);
        output[i] = (char)(ch0 << 4 | ch1);
        i++;
    }
    *output_len = i;
    return i;
}
